<template>
  <a-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs v-model="activeTab" :animated="false" :forceRender="true" @change="handleTabChange">
        <!-- 订单基本信息 -->
        <a-tab-pane key="basic" tab="订单基本信息">
          <a-form-model
            ref="form"
            :model="model"
            :rules="validatorRules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="订单编号" prop="orderNo">
                  <a-input v-model="model.orderNo" placeholder="系统自动生成" :disabled="true"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="订单状态" prop="status">
                  <j-dict-select-tag
                    v-model="model.status"
                    dictCode="order_status"
                    placeholder="请选择订单状态"
                    :disabled="!model.id"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="销售负责人" prop="salesPersonId" required>
                  <j-select-employee-modal
                    v-model="model.salesPersonId"
                    :trigger-change="true"
                    :multiple="false"
                    :departName="'销售部'"
                    placeholder="请选择销售负责人"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="客户" prop="customerId" required>
                  <j-select-customer-modal
                    v-model="model.customerId"
                    @change="handleCustomerChange"
                    placeholder="请选择客户"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="工程" prop="projectId" required>
                  <j-select-project-modal
                    v-model="model.projectId"
                    :customerId="model.customerId"
                    @change="handleProjectChange"
                    placeholder="请选择工程"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="下单日期" prop="orderDate" required>
                  <a-date-picker
                    style="width: 100%"
                    v-model="model.orderDate"
                    placeholder="请选择下单日期"
                    :getCalendarContainer="getParentModal"
                    format="YYYY-MM-DD"
                    :allowClear="false"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="交货日期" prop="deliveryDate" required>
                  <a-date-picker
                    style="width: 100%"
                    v-model="model.deliveryDate"
                    placeholder="请选择交货日期"
                    :getCalendarContainer="getParentModal"
                    format="YYYY-MM-DD"
                    :allowClear="false"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="备注" prop="remark">
                  <a-textarea v-model="model.remark" placeholder="请输入备注信息" :rows="3" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-tab-pane>

        <!-- 财务信息 -->
        <a-tab-pane key="financial" tab="财务信息">
          <a-spin :spinning="confirmLoading" class="finance-tab-content">
            <!-- 财务信息汇总卡片 -->
            <a-card title="财务信息汇总" :bordered="false" style="margin-bottom: 16px">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic
                    title="销售总额"
                    :value="model.totalAmount || 0"
                    :precision="2"
                    prefix="¥"
                    :valueStyle="{ color: '#3f8600' }"
                  >
                    <template v-if="isEdit" #suffix>
                      <a-button type="link" size="small" @click="showTotalAmountModal">
                        <a-icon type="edit" />
                      </a-button>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic
                    title="成本汇总"
                    :value="model.totalCost || 0"
                    :precision="2"
                    prefix="¥"
                    :valueStyle="{ color: '#1890ff' }"
                  >
                    <template v-if="isEdit" #suffix>
                      <a-button type="link" size="small" @click="showTotalCostModal">
                        <a-icon type="edit" />
                      </a-button>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic
                    title="利润"
                    :value="calculateProfit()"
                    :precision="2"
                    prefix="¥"
                    :valueStyle="calculateProfit() > 0 ? { color: '#52c41a' } : { color: '#cf1322' }"
                  />
                </a-col>
              </a-row>
              <a-row :gutter="16" style="margin-top: 16px">
                <a-col :span="8">
                  <a-statistic
                    title="实收金额"
                    :value="calculateReceivedAmount()"
                    :precision="2"
                    prefix="¥"
                    :valueStyle="{ color: '#52c41a' }"
                  />
                </a-col>
                <a-col :span="8">
                  <a-statistic
                    title="未收款金额"
                    :value="calculateUnpaidAmount()"
                    :precision="2"
                    prefix="¥"
                    :valueStyle="calculateUnpaidAmount() > 0 ? { color: '#cf1322' } : { color: '#52c41a' }"
                  />
                </a-col>
              </a-row>
            </a-card>

            <!-- 交易记录表格 -->
            <a-card title="交易记录" :bordered="false">
              <div v-if="!isView" class="transaction-table-header">
                <a-button type="primary" icon="plus" @click="handleAddTransaction">添加交易记录</a-button>
              </div>
              <a-table
                :columns="isView ? transactionColumnsReadOnly : transactionColumns"
                :dataSource="transactionList"
                :pagination="false"
                :rowKey="(record) => record.id || record.tempId"
                class="transaction-table finance-table j-table-force-nowrap"
                size="middle"
                bordered
                style="margin-top: 8px"
                :scroll="{ y: 300, x: true }"
              >
                <template slot="transactionTypeSlot" slot-scope="text, record">
                  <j-dict-select-tag
                    v-if="record.editable && !isView"
                    v-model="record.transactionType"
                    placeholder="请选择交易类型"
                    dictCode="transaction_type"
                    type="list"
                    :getPopupContainer="getParentModal"
                    style="width: 100px"
                  />
                  <j-dict-tag v-else :value="text" dictCode="transaction_type" />
                </template>

                <template slot="paymentMethodSlot" slot-scope="text, record">
                  <j-dict-select-tag
                    v-if="record.editable && !isView"
                    v-model="record.paymentMethod"
                    placeholder="请选择支付方式"
                    dictCode="payment_method"
                    type="list"
                    :getPopupContainer="getParentModal"
                    style="width: 100px"
                  />
                  <j-dict-tag v-else :value="text" dictCode="payment_method" />
                </template>

                <template slot="amountSlot" slot-scope="text, record">
                  <a-input-number
                    v-if="record.editable && !isView"
                    v-model="record.amount"
                    style="width: 100%"
                    :precision="2"
                    :min="0"
                  />
                  <span
                    v-else
                    style="font-weight: 500"
                    :style="{ color: parseFloat(text) < 0 ? '#f5222d' : '#52c41a' }"
                  >
                    {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
                  </span>
                </template>

                <template slot="transactionPersonIdSlot" slot-scope="text, record">
                  <j-select-employee-modal
                    v-if="record.editable && !isView"
                    v-model="record.transactionPersonId"
                    :trigger-change="true"
                    :multiple="false"
                    :departName="'销售部'"
                    placeholder="请选择交易人员"
                    @change="(value, option) => handlePersonChange(value, option, record)"
                    style="width: 100%"
                    :getPopupContainer="getParentModal"
                  ></j-select-employee-modal>
                  <span v-else>{{ record.transactionPersonName }}</span>
                </template>

                <template slot="paymentVoucherSlot" slot-scope="text, record">
                  <j-upload
                    v-if="record.editable && !isView"
                    v-model="record.paymentVoucher"
                    :uploadAction="uploadAction"
                    :multiple="false"
                    :returnUrl="true"
                  ></j-upload>
                  <div
                    v-else-if="record.paymentVoucher && isImageFile(record.paymentVoucher)"
                    class="voucher-thumbnail-container"
                    @click="previewVoucher(record.paymentVoucher)"
                  >
                    <img
                      :src="getFullImageUrl(record.paymentVoucher)"
                      class="voucher-thumbnail"
                      alt="凭证缩略图"
                      @error="handleImageError"
                    />
                  </div>
                  <div
                    v-else-if="record.transactionVoucher && isImageFile(record.transactionVoucher)"
                    class="voucher-thumbnail-container"
                    @click="previewVoucher(record.transactionVoucher)"
                  >
                    <img
                      :src="getFullImageUrl(record.transactionVoucher)"
                      class="voucher-thumbnail"
                      alt="凭证缩略图"
                      @error="handleImageError"
                    />
                  </div>
                  <a
                    v-else-if="record.paymentVoucher"
                    @click="previewVoucher(record.paymentVoucher)"
                    class="voucher-link"
                    >查看凭证</a
                  >
                  <a
                    v-else-if="record.transactionVoucher"
                    @click="previewVoucher(record.transactionVoucher)"
                    class="voucher-link"
                    >查看凭证</a
                  >
                  <span v-else>无</span>
                </template>

                <template slot="descriptionSlot" slot-scope="text, record">
                  <a-textarea
                    v-if="record.editable && !isView"
                    v-model="record.description"
                    placeholder="请输入交易描述"
                    :rows="2"
                    :autoSize="{ minRows: 2, maxRows: 4 }"
                    class="description-textarea"
                  />
                  <div v-else class="description-content">
                    <a-tooltip :title="text" placement="topLeft" v-if="text && text.length > 30">
                      <span>{{ text.slice(0, 30) }}...</span>
                    </a-tooltip>
                    <span v-else-if="text">{{ text }}</span>
                    <span v-else class="empty-description">暂无描述信息</span>
                  </div>
                </template>

                <template slot="actionSlot" slot-scope="text, record, index">
                  <div v-if="record.editable && !isView">
                    <a @click="() => saveTransaction(record, index)" class="action-btn">保存</a>
                    <a-divider type="vertical" />
                    <a @click="() => cancelEdit(record, index)" class="action-btn">取消</a>
                  </div>
                  <div v-else-if="!isView">
                    <a @click="() => editTransaction(record, index)" class="action-btn">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定删除吗?" @confirm="() => removeTransaction(record, index)">
                      <a class="action-btn">删除</a>
                    </a-popconfirm>
                  </div>
                </template>
              </a-table>
            </a-card>
          </a-spin>
        </a-tab-pane>

        <!-- 半成品订单明细 -->
        <a-tab-pane key="details" tab="半成品订单明细">
          <div style="margin-bottom: 16px" v-if="!isView">
            <a-button type="primary" icon="plus" @click="handleBatchAddMaterials">批量添加物料</a-button>
            <a-button
              type="danger"
              icon="delete"
              @click="handleDeleteDetail"
              :disabled="selectedDetailKeys.length === 0"
              style="margin-left: 8px"
              >删除选中</a-button
            >
          </div>

          <a-table
            :columns="detailColumns"
            :dataSource="detailList"
            :pagination="false"
            :rowSelection="!isView ? detailRowSelection : null"
            rowKey="tempId"
            size="small"
            bordered
            :scroll="{ y: 400 }"
          >
            <template slot="materialCode" slot-scope="text, record">
              <span>{{ record.materialCode }}</span>
            </template>

            <template slot="materialName" slot-scope="text, record">
              <a-input v-if="!isView" v-model="record.materialName" placeholder="物料名称" />
              <span v-else>{{ record.materialName }}</span>
            </template>

            <template slot="specification" slot-scope="text, record">
              <a-input v-if="!isView" v-model="record.specification" placeholder="规格型号" />
              <span v-else>{{ record.specification }}</span>
            </template>

            <template slot="unit" slot-scope="text, record">
              <a-input v-if="!isView" v-model="record.unit" placeholder="单位" />
              <span v-else>{{ record.unit }}</span>
            </template>

            <template slot="unitCost" slot-scope="text, record, index">
              <a-input-number
                v-if="!isView"
                v-model="record.unitCost"
                :min="0"
                :precision="2"
                placeholder="单位成本"
                style="width: 100%"
                @change="() => calculateDetailAmount(index)"
              />
              <span v-else>¥{{ formatMoney(record.unitCost) }}</span>
            </template>

            <template slot="quantity" slot-scope="text, record, index">
              <a-input-number
                v-if="!isView"
                v-model="record.quantity"
                :min="0"
                :precision="2"
                placeholder="数量"
                style="width: 100%"
                @change="() => calculateDetailAmount(index)"
              />
              <span v-else>{{ record.quantity }}</span>
            </template>

            <template slot="unitPrice" slot-scope="text, record, index">
              <a-input-number
                v-if="!isView"
                v-model="record.unitPrice"
                :min="0"
                :precision="2"
                placeholder="单价"
                style="width: 100%"
                @change="() => calculateDetailAmount(index)"
              />
              <span v-else>¥{{ formatMoney(record.unitPrice) }}</span>
            </template>

            <template slot="subtotal" slot-scope="text, record">
              <span>¥{{ formatMoney(record.subtotal) }}</span>
            </template>

            <template slot="action" slot-scope="text, record, index" v-if="!isView">
              <a-button type="link" size="small" @click="handleDeleteSingleDetail(index)">删除</a-button>
            </template>
          </a-table>

          <!-- 金额汇总 -->
          <a-row :gutter="24" style="margin-top: 16px; padding: 16px; background: #fafafa; border-radius: 4px">
            <a-col :span="24" style="text-align: right">
              <div style="font-size: 16px; font-weight: bold; color: #1890ff">
                订单总金额: ¥{{ formatMoney(totalAmount) }}
              </div>
            </a-col>
          </a-row>
        </a-tab-pane>

        <!-- 订单进度 - 仅在编辑和查看模式下显示 -->
        <a-tab-pane key="progress" tab="订单进度" v-if="model.id">
          <div class="progress-container">
            <div class="progress-header">
              <h3>订单进度记录</h3>
            </div>
            <a-timeline class="order-progress-timeline">
              <a-timeline-item
                v-for="(progress, index) in progressList"
                :key="index"
                :color="getProgressColor(progress.newStatus, index === 0)"
              >
                <div class="progress-item" :class="{ 'latest-item': index === 0 }">
                  <div class="progress-item-header">
                    <div class="progress-main-info">
                      <span class="progress-type">
                        <a-tag :color="getProgressColor(progress.newStatus, index === 0)">
                          {{ getProgressTypeText(progress.newStatus) }}
                        </a-tag>
                      </span>
                      <span class="progress-time">{{ progress.createTime }}</span>
                    </div>
                  </div>
                  <div class="progress-content">
                    <div class="progress-reason">
                      <span class="reason-label">变更原因：</span>
                      <span class="reason-content">{{ progress.changeReason || '无' }}</span>
                    </div>
                  </div>
                  <div class="progress-footer">
                    <span class="progress-operator"
                      >操作人: {{ progress.operatorName || progress.createBy_dictText || progress.createBy }}</span
                    >
                    <span class="update-time" v-if="progress.updateTime">更新于: {{ progress.updateTime }}</span>
                  </div>
                </div>
              </a-timeline-item>

              <a-timeline-item v-if="progressList.length === 0" color="gray">
                <div class="empty-progress">
                  <a-empty description="暂无进度记录" />
                </div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>

    <!-- 销售总额编辑模态框 -->
    <a-modal
      title="编辑销售总额"
      :visible="totalAmountModalVisible"
      @ok="handleTotalAmountOk"
      @cancel="handleTotalAmountCancel"
      :maskClosable="false"
    >
      <a-form-model
        ref="totalAmountForm"
        :model="totalAmountModel"
        :rules="totalAmountRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="销售总额" prop="totalAmount">
          <a-input-number
            v-model="totalAmountModel.totalAmount"
            :min="0"
            :precision="2"
            placeholder="请输入销售总额"
            style="width: 100%"
          />
        </a-form-item>
      </a-form-model>
    </a-modal>

    <!-- 成本汇总编辑模态框 -->
    <a-modal
      title="编辑成本汇总"
      :visible="totalCostModalVisible"
      @ok="handleTotalCostOk"
      @cancel="handleTotalCostCancel"
      :maskClosable="false"
    >
      <a-form-model
        ref="totalCostForm"
        :model="totalCostModel"
        :rules="totalCostRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="成本汇总" prop="totalCost">
          <a-input-number
            v-model="totalCostModel.totalCost"
            :min="0"
            :precision="2"
            placeholder="请输入成本汇总"
            style="width: 100%"
          />
        </a-form-item>
      </a-form-model>
    </a-modal>

    <!-- 进度记录弹窗 -->
    <a-modal
      title="进度记录"
      :visible="progressModalVisible"
      @ok="handleProgressOk"
      @cancel="handleProgressCancel"
      :confirmLoading="progressLoading"
    >
      <a-form-model
        ref="progressForm"
        :model="progressModel"
        :rules="progressRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="操作类型" prop="operationType">
          <a-input v-model="progressModel.operationType" placeholder="请输入操作类型" />
        </a-form-item>
        <a-form-item label="操作内容" prop="operationContent">
          <a-textarea v-model="progressModel.operationContent" placeholder="请输入操作内容" :rows="3" />
        </a-form-item>
        <a-form-item label="备注" prop="remark">
          <a-textarea v-model="progressModel.remark" placeholder="请输入备注" :rows="2" />
        </a-form-item>
      </a-form-model>
    </a-modal>

    <!-- 批量添加物料模态框 -->
    <a-modal
      title="批量选择物料"
      :visible="batchMaterialModalVisible"
      @ok="handleBatchMaterialOk"
      @cancel="handleBatchMaterialCancel"
      :width="1200"
      :maskClosable="false"
    >
      <j-select-material
        ref="batchMaterialSelector"
        v-model="batchSelectedMaterialIds"
        :multiple="true"
        mode="multiple"
        placeholder="请选择物料"
        @change="handleBatchMaterialChange"
      />
      <div v-if="batchSelectedMaterials.length > 0" style="margin-top: 16px">
        <h4>已选择的物料（{{ batchSelectedMaterials.length }}件）：</h4>
        <a-table
          :columns="batchMaterialColumns"
          :dataSource="batchSelectedMaterials"
          :pagination="false"
          size="small"
          bordered
          :scroll="{ y: 200 }"
          rowKey="id"
        >
          <template slot="unitCost" slot-scope="text">
            <span>¥{{ formatMoney(text) }}</span>
          </template>
        </a-table>
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import {
  addSemiProductSalesOrderTransaction,
  addSemiProductSalesOrderProgress,
  getSemiProductSalesOrderDetailByOrderId,
} from '@/api/oms/semiProductSalesOrder'
import moment from 'moment'
import JSelectCustomerModal from '@/components/jeecgbiz/JSelectCustomerModal'
import JSelectProjectModal from '@/components/jeecgbiz/JSelectProjectModal'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'

export default {
  name: 'SemiProductSalesOrderModal',
  components: {
    JSelectCustomerModal,
    JSelectProjectModal,
    JSelectEmployeeModal,
    JSelectMaterial,
  },
  data() {
    return {
      title: '',
      width: 800,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        salesPersonId: { rules: [{ required: true, message: '请选择销售负责人!' }] },
        customerId: { rules: [{ required: true, message: '请选择客户!' }] },
        projectId: { rules: [{ required: true, message: '请选择项目!' }] },
        orderAmount: { rules: [{ required: true, message: '请输入订单金额!' }] },
        orderDate: { rules: [{ required: true, message: '请选择下单日期!' }] },
        deliveryDate: { rules: [{ required: true, message: '请选择交货日期!' }] },
      },
      url: {
        add: '/oms/semiProductSalesOrder/add',
        edit: '/oms/semiProductSalesOrder/edit',
        customerList: '/crm/customer/list',
        projectList: '/crm/project/list',
        transactionList: '/oms/semiProductSalesOrderTransaction/getByOrderId',
        progressList: '/oms/semiProductSalesOrderProgress/getByOrderId',
      },
      // Tab相关数据
      activeTab: '1',
      transactionData: [],
      progressData: [],
      transactionLoading: false,
      progressLoading: false,
      // 模态框状态
      isEdit: false,
      isView: false,
      // 订单明细数据
      detailList: [],
      // 模型默认值备份
      modelDefault: {},
      selectedDetailKeys: [],
      detailColumns: [
        {
          title: '物料编号',
          dataIndex: 'materialCode',
          width: 150,
          scopedSlots: { customRender: 'materialCode' },
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 200,
          scopedSlots: { customRender: 'materialName' },
        },
        {
          title: '规格型号',
          dataIndex: 'specification',
          width: 150,
          scopedSlots: { customRender: 'specification' },
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80,
          scopedSlots: { customRender: 'amount' },
        },
        {
          title: '单位成本',
          dataIndex: 'unitCost',
          width: 120,
          scopedSlots: { customRender: 'unitCost' },
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 120,
          scopedSlots: { customRender: 'quantity' },
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          width: 120,
          scopedSlots: { customRender: 'unitPrice' },
        },
        {
          title: '小计',
          dataIndex: 'subtotal',
          width: 120,
          scopedSlots: { customRender: 'subtotal' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          scopedSlots: { customRender: 'action' },
        },
      ],
      detailRowSelection: {
        onChange: (selectedRowKeys) => {
          this.selectedDetailKeys = selectedRowKeys
        },
      },
      // 交易记录相关
      transactionList: [],
      editingTransactionId: null,
      transactionColumns: [
        {
          title: '交易类型',
          dataIndex: 'transactionType',
          width: 120,
          scopedSlots: { customRender: 'transactionTypeSlot' },
        },
        {
          title: '支付方式',
          dataIndex: 'paymentMethod',
          width: 120,
          scopedSlots: { customRender: 'paymentMethodSlot' },
        },
        {
          title: '交易金额',
          dataIndex: 'amount',
          width: 120,
          scopedSlots: { customRender: 'amountSlot' },
        },
        {
          title: '交易人员',
          dataIndex: 'transactionPersonId',
          width: 120,
          scopedSlots: { customRender: 'transactionPersonIdSlot' },
        },
        {
          title: '交易时间',
          dataIndex: 'transactionTime',
          width: 150,
        },
        {
          title: '支付凭证',
          dataIndex: 'paymentVoucher',
          width: 120,
          scopedSlots: { customRender: 'paymentVoucherSlot' },
        },
        {
          title: '交易描述',
          dataIndex: 'description',
          width: 200,
          scopedSlots: { customRender: 'descriptionSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 120,
          scopedSlots: { customRender: 'actionSlot' },
        },
      ],
      transactionColumnsReadOnly: [
        {
          title: '交易类型',
          dataIndex: 'transactionType',
          width: 120,
          scopedSlots: { customRender: 'transactionTypeSlot' },
        },
        {
          title: '支付方式',
          dataIndex: 'paymentMethod',
          width: 120,
          scopedSlots: { customRender: 'paymentMethodSlot' },
        },
        {
          title: '交易金额',
          dataIndex: 'amount',
          width: 120,
          scopedSlots: { customRender: 'amountSlot' },
        },
        {
          title: '交易人员',
          dataIndex: 'transactionPersonId',
          width: 120,
          scopedSlots: { customRender: 'transactionPersonIdSlot' },
        },
        {
          title: '交易时间',
          dataIndex: 'transactionTime',
          width: 150,
        },
        {
          title: '支付凭证',
          dataIndex: 'paymentVoucher',
          width: 120,
          scopedSlots: { customRender: 'paymentVoucherSlot' },
        },
        {
          title: '交易描述',
          dataIndex: 'description',
          width: 200,
          scopedSlots: { customRender: 'descriptionSlot' },
        },
      ],
      uploadAction: '/sys/common/upload',
      // 进度记录相关
      progressList: [],
      progressModalVisible: false,
      progressModel: {},
      progressRules: {
        operationType: [{ required: true, message: '请输入操作类型!' }],
        operationContent: [{ required: true, message: '请输入操作内容!' }],
      },
      // 用户缓存
      userCache: {},
      // 销售总额编辑相关
      totalAmountModalVisible: false,
      totalAmountModel: {},
      totalAmountRules: {
        totalAmount: [{ required: true, message: '请输入销售总额!' }],
      },
      // 成本汇总编辑相关
      totalCostModalVisible: false,
      totalCostModel: {},
      totalCostRules: {
        totalCost: [{ required: true, message: '请输入成本汇总!' }],
      },
      // 批量添加物料相关
      batchMaterialModalVisible: false,
      batchSelectedMaterialIds: '',
      batchSelectedMaterials: [],
      batchMaterialColumns: [
        {
          title: '物料编号',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 150,
        },
        {
          title: '规格型号',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80,
        },
        {
          title: '单位成本',
          dataIndex: 'unitCost',
          width: 100,
          scopedSlots: { customRender: 'unitCost' },
        },
      ],
      // 表单禁用状态
      disableSubmit: false,
    }
  },
  computed: {
    totalAmount() {
      return this.detailList.reduce((sum, item) => {
        return sum + (item.quantity * item.unitPrice || 0)
      }, 0)
    },
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.activeTab = 'basic'
      this.detailList = []
      this.selectedDetailKeys = []
      this.transactionList = []
      this.progressList = []

      // 设置默认值
      if (!this.model.id) {
        this.title = '新增半成品销售订单'
        this.isEdit = true
        this.isView = false
        this.model.orderDate = moment()
        this.model.status = 0
        this.model.totalAmount = 0
        this.model.paidAmount = 0
        this.model.paymentStatus = 0
      } else {
        this.title = '编辑半成品销售订单'
        this.isEdit = true
        this.isView = false

        // 处理日期字段，直接转换model中的日期
        if (this.model.orderDate && typeof this.model.orderDate === 'string') {
          this.model.orderDate = moment(this.model.orderDate)
        }
        if (this.model.deliveryDate && typeof this.model.deliveryDate === 'string') {
          this.model.deliveryDate = moment(this.model.deliveryDate)
        }

        // 编辑时加载相关数据
        this.loadDetailData()
        this.loadTransactionData()
        this.loadProgressData()
      }
    },
    view(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.activeTab = 'basic'
      this.title = '查看半成品销售订单'
      this.isEdit = false
      this.isView = true

      // 处理日期字段并设置表单值
      const formValues = {}
      if (this.model.orderDate) {
        if (typeof this.model.orderDate === 'string') {
          formValues.orderDate = moment(this.model.orderDate)
        } else {
          formValues.orderDate = this.model.orderDate
        }
      }
      if (this.model.deliveryDate) {
        if (typeof this.model.deliveryDate === 'string') {
          formValues.deliveryDate = moment(this.model.deliveryDate)
        } else {
          formValues.deliveryDate = this.model.deliveryDate
        }
      }

      // 设置表单字段值
      this.$nextTick(() => {
        this.form.setFieldsValue(formValues)
      })

      this.loadDetailData()
      this.loadTransactionData()
      this.loadProgressData()
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      console.log('handleOk called')
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        console.log('Form validation result:', valid)
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl = this.url.add
            method = 'post'
          } else {
            httpurl = this.url.edit
            method = 'put'
          }

          // 准备提交数据
          let formData = Object.assign({}, this.model)

          // 处理日期格式
          if (formData.orderDate && moment.isMoment(formData.orderDate)) {
            formData.orderDate = formData.orderDate.format('YYYY-MM-DD')
          }
          if (formData.deliveryDate && moment.isMoment(formData.deliveryDate)) {
            formData.deliveryDate = formData.deliveryDate.format('YYYY-MM-DD')
          }

          // 添加明细数据
          formData.detailList = this.detailList.map((item) => ({
            ...item,
            subtotal: item.quantity * item.unitPrice || 0,
          }))

          // 添加交易记录数据
          if (this.transactionList && this.transactionList.length > 0) {
            formData.transactionList = this.transactionList
              .filter((transaction) => transaction.amount && parseFloat(transaction.amount) > 0)
              .map((transaction) => ({
                ...transaction,
                amount: parseFloat(transaction.amount) || 0,
                transactionType: parseInt(transaction.transactionType) || 1,
                paymentMethod: parseInt(transaction.paymentMethod) || 1,
              }))
          }

          // 计算总金额
          formData.totalAmount = this.totalAmount

          console.log('Submitting data:', formData)
          console.log('URL:', httpurl, 'Method:', method)

          httpAction(httpurl, formData, method)
            .then((res) => {
              console.log('Response:', res)
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch((error) => {
              console.error('Submit error:', error)
              that.$message.error('提交失败：' + (error.message || '未知错误'))
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleCustomerChange(value) {
      // 客户变更时的处理逻辑
      console.log('客户变更:', value)
    },
    handleProjectChange(value) {
      // 工程变更时的处理逻辑
      console.log('工程变更:', value)
    },
    handleDeleteDetail() {
      this.detailList = this.detailList.filter((item) => !this.selectedDetailKeys.includes(item.tempId))
      this.selectedDetailKeys = []
    },
    handleDeleteSingleDetail(index) {
      this.detailList.splice(index, 1)
    },
    handleMaterialChange(materialId, materials, index) {
      // 根据物料ID和物料信息更新明细
      console.log('handleMaterialChange called......................:', { materialId, materials, index })
      if (materialId && materials && materials.length > 0) {
        const material = materials[0] // 取第一个选中的物料
        console.log('Selected material.................................:', material)
        console.log('Material keys:', Object.keys(material))

        // 尝试多种可能的字段名
        const materialCode = material.materialCode || material.code || material.materialNo || material.itemCode || ''
        const materialName = material.materialName || material.name || material.itemName || ''
        console.log('Extracted materialCode:', materialCode)
        console.log('Extracted materialName:', materialName)
        this.$set(this.detailList[index], 'materialId', materialId)
        this.$set(this.detailList[index], 'materialCode', materialCode)
        this.$set(this.detailList[index], 'materialName', materialName)
        this.$set(this.detailList[index], 'specification', material.specification || material.spec || '')
        this.$set(this.detailList[index], 'unit', material.unit || material.unitName || '')
        this.$set(this.detailList[index], 'unitCost', material.unitCost || material.cost || 0)
        this.$set(this.detailList[index], 'unitPrice', material.unitCost || material.cost || material.price || 0)

        // 重新计算小计
        this.calculateDetailAmount(index)
      } else {
        // 清空物料信息
        this.$set(this.detailList[index], 'materialId', '')
        this.$set(this.detailList[index], 'materialCode', '')
        this.$set(this.detailList[index], 'materialName', '')
        this.$set(this.detailList[index], 'specification', '')
        this.$set(this.detailList[index], 'unit', '')
        this.$set(this.detailList[index], 'unitCost', 0)
        this.$set(this.detailList[index], 'unitPrice', 0)
        this.calculateDetailAmount(index)
      }
    },
    calculateDetailAmount(index) {
      // 计算明细金额
      const detail = this.detailList[index]
      if (detail.quantity && detail.unitPrice) {
        detail.subtotal = detail.quantity * detail.unitPrice
      }
      // 更新财务汇总
      this.updateFinancialSummary()
    },
    updateFinancialSummary() {
      // 计算销售总额（基于小计汇总）
      const totalSalesAmount = this.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.subtotal) || 0)
      }, 0)

      // 计算成本汇总（基于物料单位成本 * 数量）
      const totalCost = this.detailList.reduce((sum, item) => {
        const unitCost = parseFloat(item.unitCost) || 0
        const quantity = parseFloat(item.quantity) || 0
        return sum + unitCost * quantity
      }, 0)

      // 更新模型中的财务信息
      this.$set(this.model, 'totalAmount', totalSalesAmount)
      this.$set(this.model, 'totalCost', totalCost)
    },
    loadDetailData() {
      // 加载订单明细数据
      if (this.model.id) {
        // 这里应该调用API加载明细数据
        // getSemiProductSalesOrderDetailByOrderId(this.model.id).then(res => {
        //   if (res.success) {
        //     this.detailList = res.result || [];
        //   }
        // });
      }
    },

    // 获取操作人信息
    getOperatorInfo(progress) {
      if (!progress || !progress.createBy) return

      // 如果缓存中存在，直接使用
      if (this.userCache && this.userCache[progress.createBy]) {
        progress.operatorName = this.userCache[progress.createBy]
        return
      }

      // 确保userCache存在
      if (!this.userCache) {
        this.userCache = {}
      }

      // 通过用户ID获取员工信息
      this.getEmployeeNameByUserId(progress.createBy).then((empName) => {
        progress.operatorName = empName
        // 强制更新视图
        this.$forceUpdate()
      })
    },

    // 通过createBy(userId)获取员工真实姓名
    getEmployeeNameByUserId(userId) {
      // 如果缓存中存在，直接返回
      if (this.userCache && this.userCache[userId]) {
        return Promise.resolve(this.userCache[userId])
      }

      // 确保userCache存在
      if (!this.userCache) {
        this.userCache = {}
      }

      return new Promise((resolve) => {
        httpAction('/sys/employee/queryById', { id: userId }, 'get')
          .then((res) => {
            if (res.success && res.result) {
              const empName = res.result.empName || '未知员工'
              // 缓存用户信息
              this.userCache[userId] = empName
              resolve(empName)
            } else {
              this.userCache[userId] = '未知员工'
              resolve('未知员工')
            }
          })
          .catch(() => {
            this.userCache[userId] = '未知员工'
            resolve('未知员工')
          })
      })
    },
    // 财务信息相关方法
    formatMoney(amount) {
      return amount ? parseFloat(amount).toFixed(2) : '0.00'
    },
    getUrgencyText(level) {
      const textMap = {
        1: '低',
        2: '中',
        3: '高',
        4: '紧急',
      }
      return textMap[level] || '未设置'
    },
    getUrgencyColor(level) {
      switch (level) {
        case 1:
          return '#52c41a'
        case 2:
          return '#1890ff'
        case 3:
          return '#fa8c16'
        case 4:
          return '#f5222d'
        default:
          return '#d9d9d9'
      }
    },
    getPaymentStatusColor(status) {
      switch (status) {
        case 0: // 未付款
          return '#f5222d'
        case 1: // 部分付款
          return '#fa8c16'
        case 2: // 已付清
          return '#52c41a'
        default:
          return '#d9d9d9'
      }
    },
    getPaymentStatusText(status) {
      const textMap = {
        0: '未付款',
        1: '部分付款',
        2: '已付清',
      }
      return textMap[status] || '未知'
    },
    getStatusText(status) {
      const textMap = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '生产中',
        4: '已完成',
        5: '已取消',
      }
      return textMap[status] || '未知'
    },
    // 获取进度类型对应的颜色
    getProgressColor(progressType, isLatest = false) {
      // 如果是最新状态，使用蓝色系
      if (isLatest) {
        switch (parseInt(progressType)) {
          case 0:
            return '#1890ff' // 草稿
          case 1:
            return '#2f54eb' // 待审核
          case 2:
            return '#1890ff' // 已审核
          case 3:
            return '#1890ff' // 生产中
          case 4:
            return '#1890ff' // 已完成
          case 5:
            return '#f5222d' // 已取消
          default:
            return 'blue' // 其他类型
        }
      } else {
        // 其余状态使用绿色系
        switch (parseInt(progressType)) {
          case 0:
            return '#52c41a' // 草稿
          case 1:
            return '#52c41a' // 待审核
          case 2:
            return '#52c41a' // 已审核
          case 3:
            return '#52c41a' // 生产中
          case 4:
            return '#52c41a' // 已完成
          case 5:
            return '#f5222d' // 已取消
          default:
            return 'gray' // 其他类型
        }
      }
    },

    // 获取进度类型对应的文本
    getProgressTypeText(progressType) {
      // 根据进度类型返回对应的文本描述
      switch (parseInt(progressType)) {
        case 0:
          return '草稿'
        case 1:
          return '待审核'
        case 2:
          return '已审核'
        case 3:
          return '生产中'
        case 4:
          return '已完成'
        case 5:
          return '已取消'
        default:
          return '其他'
      }
    },
    // 日期变更处理
    handleOrderDateChange(date) {
      if (date && this.model.deliveryDate) {
        if (moment(date).isAfter(moment(this.model.deliveryDate))) {
          this.$message.warning('订单日期不能晚于交货日期')
          this.model.orderDate = null
        }
      }
    },
    handleDeliveryDateChange(date) {
      if (date && this.model.orderDate) {
        if (moment(date).isBefore(moment(this.model.orderDate))) {
          this.$message.warning('交货日期不能早于订单日期')
          this.model.deliveryDate = null
        }
      }
    },
    // 财务计算方法
    calculateProfit() {
      return (this.model.totalAmount || 0) - (this.model.totalCost || 0)
    },
    // 计算实收金额（交易记录中所有交易金额的汇总）
    calculateReceivedAmount() {
      if (!this.transactionList || !Array.isArray(this.transactionList) || this.transactionList.length === 0) {
        return 0
      }
      return this.transactionList.reduce((total, transaction) => {
        const amount = parseFloat(transaction.amount) || 0
        return total + amount
      }, 0)
    },
    // 计算未收金额（销售总额 - 实收金额）
    calculateUnpaidAmount() {
      const totalAmount = parseFloat(this.model.totalAmount) || 0
      const receivedAmount = this.calculateReceivedAmount()
      return Math.max(0, totalAmount - receivedAmount)
    },
    // 交易记录相关方法
    handleAddTransaction() {
      const currentUser = this.$store.getters.userInfo
      getAction('/sys/employee/queryById', { id: currentUser.id })
        .then((res) => {
          let employeeInfo = null
          if (res.success && res.result) {
            employeeInfo = res.result
          }
          const newTransaction = {
            tempId: Date.now() + Math.random(),
            orderId: this.model.id,
            orderNo: this.model.orderNo,
            transactionType: '1',
            paymentMethod: '1',
            amount: 0,
            description: '预付款',
            transactionPersonId: employeeInfo ? employeeInfo.id : currentUser.id,
            transactionPersonName: employeeInfo ? employeeInfo.empName : currentUser.realname,
            transactionTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            editable: true,
            isNew: true,
          }
          this.transactionList.unshift(newTransaction)
          this.editingTransactionId = newTransaction.tempId
        })
        .catch((err) => {
          console.error('获取员工信息失败:', err)
          const newTransaction = {
            tempId: Date.now() + Math.random(),
            orderId: this.model.id,
            orderNo: this.model.orderNo,
            transactionType: '1',
            paymentMethod: '1',
            amount: 0,
            description: '预付款',
            transactionPersonId: currentUser.id,
            transactionPersonName: currentUser.realname,
            transactionTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            editable: true,
            isNew: true,
          }
          this.transactionList.unshift(newTransaction)
          this.editingTransactionId = newTransaction.tempId
        })
    },
    editTransaction(record, index) {
      this.transactionList.forEach((item, idx) => {
        if (idx !== index) {
          item.editable = false
        }
      })
      record.editable = true
      this.editingTransactionId = record.id || record.tempId
    },
    saveTransaction(record, index) {
      // 验证必填字段
      if (!record.transactionType) {
        this.$message.error('请选择交易类型')
        return
      }
      if (!record.paymentMethod) {
        this.$message.error('请选择支付方式')
        return
      }
      if (!record.amount || record.amount <= 0) {
        this.$message.error('请输入正确的交易金额')
        return
      }
      if (!record.transactionPersonId) {
        this.$message.error('请选择交易人员')
        return
      }

      record.editable = false
      this.editingTransactionId = null

      if (record.isNew) {
        // 新增交易记录
        const transactionData = {
          orderId: record.orderId,
          transactionType: record.transactionType,
          paymentMethod: record.paymentMethod,
          amount: record.amount,
          description: record.description,
          transactionPersonId: record.transactionPersonId,
          transactionTime: record.transactionTime,
          paymentVoucher: record.paymentVoucher,
        }

        // 这里可以调用API保存到后端
        console.log('保存交易记录:', transactionData)
        record.isNew = false
      } else {
        // 更新交易记录
        console.log('更新交易记录:', record)
      }

      this.$message.success('保存成功')
    },
    cancelEdit(record, index) {
      if (record.isNew) {
        this.transactionList.splice(index, 1)
      } else {
        record.editable = false
        // 恢复原始数据
        this.loadTransactionData()
      }
      this.editingTransactionId = null
    },
    removeTransaction(record, index) {
      if (record.isNew) {
        this.transactionList.splice(index, 1)
      } else {
        // 调用删除API
        console.log('删除交易记录:', record.id)
        this.transactionList.splice(index, 1)
        this.$message.success('删除成功')
      }
    },
    handlePersonChange(value, option, record) {
      if (option && option.data) {
        record.transactionPersonName = option.data.empName || option.data.realname
      }
    },
    getParentModal(triggerNode) {
      return document.body
    },
    isImageFile(url) {
      if (!url) return false
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      return imageExtensions.some((ext) => url.toLowerCase().includes(ext))
    },
    getFullImageUrl(url) {
      if (!url) return ''
      if (url.startsWith('http')) return url
      return window.location.origin + url
    },
    previewVoucher(url) {
      if (this.isImageFile(url)) {
        // 图片预览
        const img = new Image()
        img.src = this.getFullImageUrl(url)
        const newWindow = window.open('', '_blank')
        newWindow.document.write(`<img src="${img.src}" style="max-width: 100%; height: auto;"/>`)
      } else {
        // 非图片文件直接下载
        window.open(this.getFullImageUrl(url), '_blank')
      }
    },
    handleImageError(event) {
      event.target.src = '/static/images/no-image.png'
    },
    handleTransactionOk() {
      this.$refs.transactionForm.validate((valid) => {
        if (valid) {
          this.transactionLoading = true
          const formData = Object.assign({}, this.transactionModel)

          // 处理日期格式
          if (formData.transactionTime && moment.isMoment(formData.transactionTime)) {
            formData.transactionTime = formData.transactionTime.format('YYYY-MM-DD HH:mm:ss')
          }

          const apiMethod = addSemiProductSalesOrderTransaction

          apiMethod(formData)
            .then((res) => {
              if (res.success) {
                this.$message.success('保存成功')
                this.transactionModalVisible = false
                this.loadTransactionData()
              }
            })
            .finally(() => {
              this.transactionLoading = false
            })
        }
      })
    },
    handleTransactionCancel() {
      this.transactionModalVisible = false
    },
    // 进度记录相关方法
    handleAddProgress() {
      this.progressModel = {
        orderId: this.model.id,
        operationType: '',
        operationContent: '',
        operationTime: moment(),
        operatorId: this.$store.getters.userInfo.id,
        operatorName: this.$store.getters.userInfo.realname,
        remark: '',
      }
      this.progressModalVisible = true
    },
    handleProgressOk() {
      this.$refs.progressForm.validate((valid) => {
        if (valid) {
          this.progressLoading = true
          const formData = Object.assign({}, this.progressModel)

          // 处理日期格式
          if (formData.operationTime && moment.isMoment(formData.operationTime)) {
            formData.operationTime = formData.operationTime.format('YYYY-MM-DD HH:mm:ss')
          }

          addSemiProductSalesOrderProgress(formData)
            .then((res) => {
              if (res.success) {
                // 获取操作人信息
                this.getOperatorInfo(res.result)
                // 添加到列表开头
                this.progressList.unshift(res.result)
                this.$message.success('进度记录添加成功')
                this.progressModalVisible = false
              } else {
                this.$message.error('添加失败: ' + res.message)
              }
            })
            .catch((err) => {
              console.error('添加进度记录异常:', err)
              this.$message.error('添加失败')
            })
            .finally(() => {
              this.progressLoading = false
            })
        }
      })
    },
    handleProgressCancel() {
      this.progressModalVisible = false
    },
    // 销售总额编辑相关方法
    showTotalAmountModal() {
      this.totalAmountModel = {
        totalAmount: this.model.totalAmount || 0,
      }
      this.totalAmountModalVisible = true
    },
    handleTotalAmountOk() {
      this.$refs.totalAmountForm.validate((valid) => {
        if (valid) {
          this.model.totalAmount = this.totalAmountModel.totalAmount
          this.totalAmountModalVisible = false
          this.$message.success('销售总额更新成功')
        }
      })
    },
    handleTotalAmountCancel() {
      this.totalAmountModalVisible = false
      this.totalAmountModel = {}
    },
    // 成本汇总编辑相关方法
    showTotalCostModal() {
      this.totalCostModel = {
        totalCost: this.model.totalCost || 0,
      }
      this.totalCostModalVisible = true
    },
    handleTotalCostOk() {
      this.$refs.totalCostForm.validate((valid) => {
        if (valid) {
          this.model.totalCost = this.totalCostModel.totalCost
          this.totalCostModalVisible = false
          this.$message.success('成本汇总更新成功')
        }
      })
    },
    handleTotalCostCancel() {
      this.totalCostModalVisible = false
      this.totalCostModel = {}
    },
    // 批量添加物料相关方法
    handleBatchAddMaterials() {
      this.batchSelectedMaterialIds = ''
      this.batchSelectedMaterials = []
      this.batchMaterialModalVisible = true
    },
    handleBatchMaterialChange(materialIds, materials) {
      this.batchSelectedMaterials = materials || []
    },
    handleBatchMaterialOk() {
      if (this.batchSelectedMaterials.length === 0) {
        this.$message.warning('请选择至少一个物料')
        return
      }

      // 批量添加选中的物料到明细列表
      this.batchSelectedMaterials.forEach((material) => {
        const newDetail = {
          tempId: Date.now() + Math.random(),
          materialId: material.id,
          materialCode: material.materialCode,
          materialName: material.materialName,
          specification: material.specification || '',
          unit: material.unit || '',
          unitCost: material.unitCost || 0,
          quantity: 1, // 默认数量为1
          unitPrice: material.unitCost || 0,
          subtotal: material.unitCost || 0,
          remark: '',
        }
        this.detailList.push(newDetail)
      })

      // 更新财务汇总
      this.updateFinancialSummary()

      this.$message.success(`成功添加 ${this.batchSelectedMaterials.length} 个物料明细`)
      this.batchMaterialModalVisible = false
      this.batchSelectedMaterialIds = ''
      this.batchSelectedMaterials = []
    },
    handleBatchMaterialCancel() {
      this.batchMaterialModalVisible = false
      this.batchSelectedMaterialIds = ''
      this.batchSelectedMaterials = []
    },
    // Tab切换相关方法
    handleTabChange(activeKey) {
      this.activeTab = activeKey
      // 根据切换的Tab动态加载数据
      if (activeKey === 'transaction' && this.model.id) {
        this.loadTransactionData()
      } else if (activeKey === 'progress' && this.model.id) {
        this.loadProgressData()
      } else if (activeKey === 'detail' && this.model.id) {
        this.loadDetailData()
      }
    },
    // 更新现有的加载交易记录数据方法以支持Tab切换
    loadTransactionData() {
      if (!this.model.id) return

      this.transactionLoading = true
      getAction(this.url.transactionList, { orderId: this.model.id })
        .then((res) => {
          if (res.success) {
            // 同时更新transactionData和transactionList以兼容现有逻辑
            this.transactionData = res.result || []
            this.transactionList = res.result || []
          } else {
            this.$message.error('加载交易记录失败: ' + res.message)
            this.transactionData = []
            this.transactionList = []
          }
        })
        .catch((err) => {
          console.error('加载交易记录异常:', err)
          this.$message.error('加载交易记录失败')
          this.transactionData = []
          this.transactionList = []
        })
        .finally(() => {
          this.transactionLoading = false
        })
    },
    // 加载进度数据
    loadProgressData() {
      if (!this.model.id) return

      this.progressLoading = true
      getAction(this.url.progressList, { orderId: this.model.id })
        .then((res) => {
          if (res.success) {
            this.progressList = res.result || []
            this.progressData = res.result || []
            // 获取操作人信息
            this.progressList.forEach((progress) => {
              this.getOperatorInfo(progress)
            })
          } else {
            this.$message.error('加载进度记录失败: ' + res.message)
            this.progressList = []
            this.progressData = []
          }
        })
        .catch((err) => {
          console.error('加载进度记录异常:', err)
          this.$message.error('加载进度记录失败')
          this.progressList = []
          this.progressData = []
        })
        .finally(() => {
          this.progressLoading = false
        })
    },
    // 加载明细数据
    async loadDetailData() {
      if (!this.model.id) return
      try {
        const res = await getSemiProductSalesOrderDetailByOrderId(this.model.id)
        if (res.success) {
          this.detailList = res.result || []
        } else {
          this.$message.error('获取明细数据失败：' + res.message)
        }
      } catch (error) {
        console.error('加载明细数据失败:', error)
        this.$message.error('获取明细数据失败')
      }
    },
  },
}
</script>

<style scoped>
/* 财务信息样式 */
.finance-tab-content {
  min-height: 400px;
}

.transaction-table-header {
  margin-bottom: 16px;
}

.finance-table .ant-table-tbody > tr > td {
  padding: 8px 16px;
}

.transaction-table {
  border-radius: 6px;
}

/* 订单进度相关样式 */
.progress-container {
  padding: 16px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.progress-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.order-progress-timeline {
  margin-top: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}

.order-progress-timeline .ant-timeline-item {
  padding-bottom: 20px;
}

.order-progress-timeline .ant-timeline-item:last-child {
  padding-bottom: 0;
}

.progress-item {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 8px;
  transition: all 0.3s;
}

.progress-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.progress-item.latest-item {
  border-left: 3px solid #1890ff;
  background-color: #f0f7ff;
}

.progress-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.progress-main-info {
  display: flex;
  align-items: center;
}

.progress-time {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  margin-left: 10px;
}

.progress-type {
  font-weight: bold;
  text-align: center;
}

.progress-type .ant-tag {
  margin-right: 0;
  padding: 0 8px;
  font-weight: 500;
}

.progress-content {
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
  color: rgba(0, 0, 0, 0.65);
}

.progress-reason {
  display: flex;
  margin-bottom: 8px;
}

.reason-label {
  font-weight: 500;
  margin-right: 8px;
  min-width: 70px;
}

.reason-content {
  flex: 1;
  word-break: break-all;
}

.progress-footer {
  color: #888;
  font-size: 12px;
  text-align: right;
  display: flex;
  justify-content: space-between;
}

.progress-operator {
  color: rgba(0, 0, 0, 0.45);
}

.update-time {
  color: rgba(0, 0, 0, 0.45);
  font-style: italic;
}

.empty-progress {
  padding: 24px 0;
  text-align: center;
}

/* 统计卡片样式优化 */
.ant-statistic-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.ant-statistic-content {
  font-size: 20px;
  font-weight: 600;
}

/* 表格样式优化 */
.j-table-force-nowrap .ant-table-tbody > tr > td {
  white-space: nowrap;
}

/* 卡片样式 */
.ant-card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ant-card-head {
  border-bottom: 1px solid #f0f0f0;
}

.ant-card-head-title {
  font-weight: 600;
  color: #262626;
}

/* 标签页样式 */
.ant-tabs-content-holder {
  padding: 16px 0;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .progress-timeline-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .operation-time {
    margin-top: 4px;
  }
}
</style>
